﻿using System.Linq;
using Enyim.Caching;
using Ayatta.Contract;
using Web.Base.OAuth;
using System.Web.Mvc;
using Web.Base.EventArgs;
using Web.Base.Extensions;
using Ayatta.Contract.Domain;
using Ayatta.Contract.Component;

namespace Web.Passport.Controllers
{
    public class ExternalController : Controller
    {
        private IPassportService PassportService { get; set; }
        private static IMemcachedClient MemcachedClient { get; set; }
        public ExternalController(IPassportService passportService, IMemcachedClient memcachedClient)
        {
            PassportService = passportService;
            MemcachedClient = memcachedClient;
        }

        public ActionResult Index(string param)
        {
            var client = GetOAuthClient(param);

            if (client != null)
            {
                var url = client.GetLoginUri();
                return Redirect(url);
            }
            return Redirect("/");
        }

        public ActionResult Auth(string param)
        {
            var client = GetOAuthClient(param);
            if (client != null)
            {
                var result = client.Callback(Request.QueryString);
                if (result != null && result.Status)
                {
                    //var identity = new SilenthinkIdentity(user.Id, user.NickName, user.Role, string.Empty);
                    //SetAuthCookie(user.Name, remember, identity);
                    return Content(result.Data.OpenId);
                }
            }
            return Redirect("/");
        }

        private IOAuthClient GetOAuthClient(string name)
        {
            var key = CacheKey.Passport.OAuthConfigs;
            var configs = MemcachedClient.Put(key, () => PassportService.GetOAuthConfigs(true));
            var config = configs.FirstOrDefault(o => o.ClientName.ToLower() == name.ToLower());
            var client = OAuthClientFactory.Create(config);
            client.Authorized += Authorized;
            return client;
        }

        private  void Authorized(object sender, EventArgs<ExternalUser> e)
        {
            PassportService.ExternalLogin(e.Data);
        }
    }
}
